package cn.itmantzy.user.service.impl;

import cn.itmantzy.basic.exception.BusinessException;
import cn.itmantzy.basic.util.MD5Utils;
import cn.itmantzy.user.domain.Logininfo;
import cn.itmantzy.user.dto.LoginDto;
import cn.itmantzy.user.mapper.LogininfoMapper;
import cn.itmantzy.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登录业务层
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map<String, Object> loginAccount(LoginDto dto) {
        // 一：校验用户名和密码是否输入正确
        if(dto.getType() == null){
            throw new BusinessException("一定要有type!!!");
        }
        Logininfo logininfo = logininfoMapper.loadByUsername(dto);
        // 校验用户是否存在
        if (StringUtils.isEmpty(logininfo.getUsername())){
            throw new BusinessException("对不起，用户不存在！！！");
        }
        // 校验密码是否输入正确(密码比较一定要加上盐值，并且密码和盐值顺序要一致)
        String salt = logininfo.getSalt();
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        if (!logininfo.getPassword().equals(md5Pwd)){
            throw new BusinessException("密码输入错误！！！");
        }
        // 保存token和用户登录信息logininfo
        String token = UUID.randomUUID().toString();
        // 存入redis
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        // 将用户登录信息中的私密信息初始化为null，避免私密泄露
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);
        return map;
    }
}














